--优先队列

--[[
local obj = {
	id = id --物品id
	type = type --物品类型
	priority = priority --排序优先级
	message = message 
}
--]]

local table_insert = table.insert
local table_remove = table.remove

local Queue = {}

function Queue.new(...)
	local instance = setmetatable({}, {__index=Queue})
	instance:ctor(...)
	return instance
end

function Queue:ctor()
	self.obj_list = {}
end

function Queue:clear()
	self.obj_list = {}
end

--增加一个对象然后自动排序
function Queue:insert(obj)
	table_insert(self.obj_list, obj)
	self:sort()
end

--删除对象
function Queue:remove(obj)
	for i = #self.obj_list, 1, -1 do
		if self.obj_list[i].id == obj.id and self.obj_list[i].type == obj.type then
			table_remove(self.obj_list, i)
			break
		end
	end
end

--对队列排序
function Queue:sort()
	--类型一样时，按优先级
	--类型不一样时，按类型大小
	function sort_func(obj1, obj2)
		if obj1.type ==  obj2.type then
			return obj1.priority > obj2.priority
		else
			return obj1.type > obj2.type
		end
	end
	table.sort(self.obj_list, sort_func)
end

--弹出排在最后一的对象
function Queue:popTail()
	return table_remove(self.obj_list, #self.obj_list)
end

--弹出排在第一的对象
function Queue:popHead()
	return table_remove(self.obj_list, 1)
end

function Queue:has(obj)
	for k, v in ipairs(self.obj_list) do
		if v.id == id and v.type == obj.type then
			return true
		end
	end
	return false
end

function Queue:size()
	return #self.obj_list
end

function Queue:getList()
	return self.obj_list
end


----------test-----
local queue = Queue.new()

local obj = {
	id = 1,
	type = 1,
	priority = 1,
	message = "",
}
queue:insert(obj)
local obj = {
	id = 2,
	type = 1,
	priority = 2,
	message = "",
}
queue:insert(obj)
local obj = {
	id = 3,
	type = 1,
	priority = 3,
	message = "",
}
queue:insert(obj)

for k, v in ipairs(queue:getList()) do 
	print("_____type__", v.id)
end



return Queue